package com.nx.platform.es.bean.modle.query;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ListMultimap;
import com.nx.platform.es.bean.dto.RequestContext;
import com.nx.platform.es.biz.wrapper.parser.StatementOperator;
import com.nx.platform.es.common.utils.MoreMaps;
import org.elasticsearch.index.query.QueryBuilder;

import java.util.Map;

/**
 * @author
 * @since 2016年10月15日
 */
public class QueryField {

    private final String face;
    private final QueryFieldType type;
    private final ImmutableMap<String, ?> config;

    private QueryField(String face, QueryFieldType type, ImmutableMap<String, ?> config) {
        this.face = face;
        this.type = type;
        this.config = config;
    }

    public static QueryField create(Map<?, ?> settings) {
        String face = MoreMaps.getString(settings, "face");
        Preconditions.checkState(!Strings.isNullOrEmpty(face), "param face empty or null");
        String type = MoreMaps.getString(settings, "type");
        Preconditions.checkState(!Strings.isNullOrEmpty(type), "type not found");
        QueryFieldType fieldType = QueryFieldType.valueOf(type);
        ImmutableMap<String, ?> config = fieldType.getParser().parse(settings);
        return new QueryField(face, fieldType, config);
    }

    public void handle(RequestContext context, StatementOperator operator, String fieldValue,
                       ListMultimap<Boolean, QueryBuilder> queryBuilders) {
        type.getHandler().handle(config, context, face, operator, fieldValue, queryBuilders);
    }

    public String getFace() {
        return face;
    }

    public QueryFieldType getType() {
        return type;
    }

    public ImmutableMap<String, ?> getConfig() {
        return config;
    }

}
